﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Read.Api.Application.Command.UserRoleCommand;
using B.S.BaseData.Read.Api.Dtos;
using MediatR;
using SqlSugar;

namespace B.S.BaseData.Read.Api.Application.CommandHander.UserRoleHander
{
    public class GetUserRole2CommandHander : IRequestHandler<GetUserRole2Command, ApiResult<List<GetUserRole2Dto>>>
    {

        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public GetUserRole2CommandHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 属于**角色的显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<GetUserRole2Dto>>> Handle(GetUserRole2Command request, CancellationToken cancellationToken)
        {
            ApiResult<List<GetUserRole2Dto>> result = new ApiResult<List<GetUserRole2Dto>>();

            var linq = db.Queryable<User, UserRole, Role>((u, ur, r) => new object[]
            {
                JoinType.Inner, u.UserId == ur.UserId,
                JoinType.Inner, ur.RoleId == r.RoleId
            })
            .Where((u, ur, r) => request.RoleId == ur.RoleId)
            .Select((u, ur, r) => new GetUserRole2Dto
            {
                UserRoleId = ur.UserRoleId,
                UserId = u.UserId,
                UserName = u.UserName,
                RoleId = r.RoleId,
                RoleName = r.RoleName
            }).OrderBy(u => u.UserId).ToList();

            result.Code = ApiEnum.显示成功;
            result.Msg = ApiEnum.显示成功.ToString();

            result.Data = mapper.Map<List<GetUserRole2Dto>>(linq);

            return Task.FromResult(result);
        }
    }
}
